/*
 *
 */

package com.hlingsoft.kkh.action;


import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.dao.*;
import com.hlingsoft.kkh.entity.*;


import com.hlingsoft.kkh.entity.vo.EventsSearchVo;
import com.hlingsoft.kkh.entity.vo.EventsVo;
import com.hlingsoft.kkh.entity.vo.ImageVo;
import com.hlingsoft.kkh.util.Common;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 职位
 *
 * @author Herbert
 */
@Controller
@RequestMapping("/event")

public class EventsAction extends BaseAction {


    @Autowired
    private EventsDao eventsDao;


    @Autowired
    private EventCommentsDao eventCommentsDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private TagDao tagDao;


    /**
     * 添加活动现场
     */
    @RequestMapping(value = "/add.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "description") String description,
            @RequestParam(value = "createAddress") String createAddress,
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "tokeTimes",required = false) String tokeTimes,
            @RequestParam("files") MultipartFile[] files,


            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String msg = name + "活动现场已存在";
            if (eventsDao.getEventsByNameAndAddress(name, createAddress).size() != 0) {
                resultMap.put("msg", msg);
            } else {
                Events event = new Events();
                String images = "";

                List<ImageVo> imageVoList = new ArrayList<ImageVo>();

                if (tokeTimes!=null){
                    JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
                    long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);
                    for (int i = 0; i < tokeTimeArray.length; i++) {
                        ImageVo imageVo = new ImageVo();
                        imageVo.setFile(files[i]);

                        Date date = Common.transferLongToDate(tokeTimeArray[i]/1000);   //long类型转成Date类型
                        imageVo.setDate(date);
                        imageVoList.add(imageVo);
                    }
                }else {
                    for (int i = 0; i < files.length; i++) {
                        ImageVo imageVo = new ImageVo();
                        imageVo.setFile(files[i]);
                        imageVo.setDate(new Date());
                        imageVoList.add(imageVo);
                    }
                }


                for (ImageVo imageVo : imageVoList) {
                    String fileName = imageVo.getFile().getOriginalFilename();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                            imageVo.getFile().getSize());
                    images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

                }

                if (images.length() > 0) {
                    images = images.substring(0, images.length() - 1);
                }

                //添加events
                event.setName(name);
                event.setImages(images);
                event.setDescription(description);
                event.setCreateAddress(createAddress);
                event.setAppUserId(appUserId);
                event.setCreateTime(new Date());
                event.setUpdateTime(new Date());
                event.setLatitude(latitude);
                event.setLongitude(longitude);
                event.setInterestIds("1");
                eventsDao.addEvents(event);
                resultMap.put("eventId", event.getId());//返回添加的eventId
                resultMap.put("images", images);        //返回添加的images


                //添加eventsComments
                EventComments eventComments = new EventComments();
                eventComments.setContent(description);
                eventComments.setEventId(event.getId());
                eventComments.setImage(images);
                eventComments.setLikeCount(0);
                eventComments.setUnlikeCount(0);
                eventComments.setShareCount(0);
                eventComments.setAppUserId(appUserId);
                eventComments.setCreateTime(new Date());
                eventComments.setUpdateTime(new Date());
                eventComments.setType(1);
                eventCommentsDao.addEventComments(eventComments);


                //添加图片
                for (ImageVo imageVo : imageVoList) {
                    Image image = new Image();

                    //图片地址
                    String fileName = imageVo.getFile().getOriginalFilename();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                            imageVo.getFile().getSize());
                    String path = "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                    image.setPath(path);

                    image.setAppUserId(appUserId);
                    image.setEventCommentsId(eventComments.getId());
                    image.setEventsId(event.getId());
                    image.setTagId(0);
                    image.setCreateTime(new Date());
                    image.setUpdateTime(new Date());
                    image.setTokeTime(imageVo.getDate());
                    image.setAvailable(1);
                    imageDao.addImage(image);
                }

            }
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * android 创建
     * @param name
     * @param description
     * @param createAddress
     * @param appUserId
     * @param latitude
     * @param longitude
     * @param tokeTimes
     * @param file1
     * @param file2
     * @param file3
     * @param file4
     * @param request
     * @return
     */
    @RequestMapping(value = "/addB.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "description") String description,
            @RequestParam(value = "createAddress") String createAddress,
            @RequestParam(value = "appUserId") long appUserId,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "tokeTimes") String tokeTimes,
            @RequestParam(value = "file1",required = false) MultipartFile file1,
            @RequestParam(value = "file2",required = false) MultipartFile file2,
            @RequestParam(value = "file3",required = false) MultipartFile file3,
            @RequestParam(value = "file4",required = false) MultipartFile file4,


            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String msg = name + "活动现场已存在";
            if (eventsDao.getEventsByNameAndAddress(name, createAddress).size() != 0) {
                resultMap.put("msg", msg);
            } else {
                Events event = new Events();
                String images = "";

                JSONArray jsonArray = JSONArray.fromObject(tokeTimes);
                long[] tokeTimeArray = (long[]) JSONArray.toArray(jsonArray, long.class);
                List<MultipartFile> filesList = new ArrayList<MultipartFile>();
                if (file1!=null){
                    filesList.add(file1);
                }
                if (file2!=null){
                    filesList.add(file2);
                }
                if (file3!=null){
                    filesList.add(file3);
                }
                if (file4!=null){
                    filesList.add(file4);
                }

                List<ImageVo> imageVoList = new ArrayList<ImageVo>();
                for (int i = 0; i < tokeTimeArray.length; i++) {

                    ImageVo imageVo = new ImageVo();
                    imageVo.setFile(filesList.get(i));

                    Date date = Common.transferLongToDate(tokeTimeArray[i]/1000);   //long类型转成Date类型
                    imageVo.setDate(date);
                    imageVoList.add(imageVo);
                }

                for (ImageVo imageVo : imageVoList) {
                    String fileName = imageVo.getFile().getOriginalFilename();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                            imageVo.getFile().getSize());
                    images += "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName + ",";

                }

                if (images.length() > 0) {
                    images = images.substring(0, images.length() - 1);
                }

                //添加events
                event.setName(name);
                event.setImages(images);
                event.setDescription(description);
                event.setCreateAddress(createAddress);
                event.setAppUserId(appUserId);
                event.setCreateTime(new Date());
                event.setUpdateTime(new Date());
                event.setLatitude(latitude);
                event.setLongitude(longitude);
                event.setInterestIds("1");
                eventsDao.addEvents(event);
                resultMap.put("eventId", event.getId());//返回添加的eventId
                resultMap.put("images", images);        //返回添加的images


                //添加eventsComments
                EventComments eventComments = new EventComments();
                eventComments.setContent(description);
                eventComments.setEventId(event.getId());
                eventComments.setImage(images);
                eventComments.setLikeCount(0);
                eventComments.setUnlikeCount(0);
                eventComments.setShareCount(0);
                eventComments.setAppUserId(appUserId);
                eventComments.setCreateTime(new Date());
                eventComments.setUpdateTime(new Date());
                eventComments.setType(1);
                eventCommentsDao.addEventComments(eventComments);


                //添加图片
                for (ImageVo imageVo : imageVoList) {
                    Image image = new Image();

                    //图片地址
                    String fileName = imageVo.getFile().getOriginalFilename();
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    putObject(dateString, fileName, imageVo.getFile().getInputStream(),
                            imageVo.getFile().getSize());
                    String path = "http://kkh.oss-cn-hangzhou.aliyuncs.com/upload/" + dateString + "/" + fileName;
                    image.setPath(path);

                    image.setAppUserId(appUserId);
                    image.setEventCommentsId(eventComments.getId());
                    image.setEventsId(event.getId());
                    image.setTagId(0);
                    image.setCreateTime(new Date());
                    image.setUpdateTime(new Date());
                    image.setTokeTime(imageVo.getDate());
                    image.setAvailable(1);
                    imageDao.addImage(image);
                }

            }
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 现场详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "eventId") long eventId,
            @RequestParam(value = "longitude") float longitude,
            @RequestParam(value = "latitude") float latitude,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Events events = eventsDao.getEventsById(eventId);
            if (events!=null){
                List<EventComments> eventCommentsOrderList = new ArrayList<EventComments>();
                List<EventComments> imageCommentsList = eventCommentsDao.getImageCommentsListByEventId(eventId,2,0,100);
                List<EventComments> noImageCommentsList = eventCommentsDao.getNoImageCommentsListByEventId(eventId,0,100);

                for (EventComments eventComments : imageCommentsList) {
                    AppUser appUser = userDao.getUserById(eventComments.getAppUserId());
                    if (appUser!=null){
                        eventComments.setUserName(appUser.getName());
                        eventComments.setHeadImage(appUser.getHeadImage());

                        List<Image> imageList = imageDao.getImageByEventCommentsId(eventComments.getId());
                        eventComments.setImageList(imageList);

                        eventCommentsOrderList.add(eventComments);
                    }

                }

                for (EventComments eventComments : noImageCommentsList) {
                    AppUser appUser = userDao.getUserById(eventComments.getAppUserId());
                    eventComments.setUserName(appUser.getName());
                    eventComments.setHeadImage(appUser.getHeadImage());
                    eventCommentsOrderList.add(eventComments);
                }
                events.setEventCommentsList(eventCommentsOrderList);
                resultMap.put("events", events);
                resultMap.put("result", true);
            } else {
                resultMap.put("msg","该社区已被删除");
                resultMap.put("result",false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;

    }


    /**
     * 活动搜索
     *
     * @param name
     * @param request
     * @return
     */
    @RequestMapping(value = "/search.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> search(
            @RequestParam(value = "name") String name,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (Common.isWindows()) {
                name = Common.encodeStr(name);
            }
            List<Events> eventsList = eventsDao.getEventsByLikeName(name);
            resultMap.put("eventsList", eventsList);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;

    }


    /**
     * 搜索返回名字
     *
     * @param name
     * @param request
     * @return
     */
    @RequestMapping(value = "/toSearch.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> toSearch(
            @RequestParam(value = "name") String name,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (Common.isWindows()) {
                name = Common.encodeStr(name);
            }
            List<EventsSearchVo> eventsSearchVoList = new ArrayList<EventsSearchVo>();
            List<String> nameList = eventsDao.getEventsNameByLikeName(name);
            for (String name1 : nameList) {
                EventsSearchVo eventsSearchVo = new EventsSearchVo();
                eventsSearchVo.setName(name1);
                List<Events> eventsList = eventsDao.getEventsByName(name1);
                if (eventsList.size() == 1) {
                    eventsSearchVo.setId(eventsList.get(0).getId());
                    eventsSearchVo.setAddress(eventsList.get(0).getCreateAddress());
                    eventsSearchVo.setIsOnly(1);
                } else {
                    eventsSearchVo.setId(0);
                    eventsSearchVo.setIsOnly(0);
                }
                eventsSearchVo.setCount(eventsList.size());
                eventsSearchVoList.add(eventsSearchVo);
            }
            resultMap.put("eventsSearchVoList", eventsSearchVoList);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 搜索显示events的名字
     *
     * @param name
     * @param request
     * @return
     */
    @RequestMapping(value = "/toSearchList.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> toSearchList(
            @RequestParam(value = "name") String name,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (Common.isWindows()) {
                name = Common.encodeStr(name);
            }
            List<EventsVo> resultList = new ArrayList<EventsVo>();

            List<Events> eventsList = eventsDao.getEventsByName(name);
            for (Events events : eventsList) {
                EventsVo eventsVo = new EventsVo();
                eventsVo.setId(events.getId());
                eventsVo.setName(events.getName());
                eventsVo.setImages(events.getImages());

                EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());


                eventsVo.setImageList(imageList);

                eventsVo.setDescription(events.getDescription());
                eventsVo.setAppUserId(events.getAppUserId());
                eventsVo.setCreateTime(events.getCreateTime());
                eventsVo.setUpdateTime(events.getUpdateTime());
                eventsVo.setCreateAddress(events.getCreateAddress());
                eventsVo.setLatitude(events.getLatitude());
                eventsVo.setLongitude(events.getLongitude());
                eventsVo.setUpdateTime(events.getUpdateTime());
                eventsVo.setAppUser(userDao.getUserById(events.getAppUserId()));
                resultList.add(eventsVo);
            }
            resultMap.put("resultList", resultList);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 标签搜索
     *
     * @param name
     * @param request
     * @return
     */
    @RequestMapping(value = "/tagSearch.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> tagSearch(
            @RequestParam(value = "name") String name,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (Common.isWindows()) {
                name = Common.encodeStr(name);
            }
            List<Tag> tagList = tagDao.getTagByLikeName(name);
            List<String> tags = new ArrayList<String>();
            for (Tag tag : tagList) {
                tags.add(tag.getName());
            }
            resultMap.put("tags", tags);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;

    }


    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");

        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "upload/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }

}
